"""
准备:
1. 安装依赖
pip install tqdm tabulate python-dotenv
2. 提供token。在本文件同级目录创建 .env 文件，内容为：
GITCODE_TOKEN=你的token

使用: python pr.py
"""

import http.client
import json
import os

from tabulate import tabulate
from tqdm import tqdm
from dotenv import load_dotenv

load_dotenv() 

token = os.getenv("GITCODE_TOKEN")


def get_prs() -> list[dict]:
    conn = http.client.HTTPSConnection("api.gitcode.com")
    payload = ""
    conn.request(
        "GET",
        f"/api/v5/repos/openharmony-sig/ohos_react_native/pulls?state=open&access_token={token}&page=1&per_page=100",
    )
    res = conn.getresponse()
    prs = json.loads(res.read())
    return prs


def can_merge(pr_id: id) -> tuple[bool, list[str]]:
    conn = http.client.HTTPSConnection("api.gitcode.com")
    conn.request(
        "GET",
        f"/api/v5/repos/openharmony-sig/ohos_react_native/pulls/{pr_id}?access_token={token}",
    )
    res = conn.getresponse()
    detail = json.loads(res.read())
    labels = list(l["name"] for l in detail["labels"])

    checks = {
        "conflict_passed": "有冲突",
        "work_in_progress_passed": "是草稿",
        "resolve_discussion_passed": "有没解决的评审意见",
        "approval_reviewers_required_passed": "少评审人点分",
        # "approval_testers_required_passed": "流水线没过",
        # "approval_approvers_required_passed": "审查人员"
    }
    reasons = []
    for field, reason in checks.items():
        if not detail["mergeable_state"].get(field, False):
            reasons.append(reason)
    if not "静态检查成功" in labels:
        reasons.append("codecheck没过")
    if not "编译成功" in labels:
        reasons.append("构建没过")
    return len(reasons) == 0, reasons


prs = get_prs()
res = []
for pr in tqdm(prs):
    # # 过滤标题包含指定字符串
    # if "doc" not in pr["title"]:
    #     continue
    if pr["draft"]:
        continue

    can_merge_flag, reasons = can_merge(pr["number"])
    res.append(
        (
            pr["html_url"],
            can_merge_flag,
            pr["user"]["login"],
            ",".join(reasons),
            pr["title"][:64],
        )
    )

res.sort(key=lambda x: x[1], reverse=True)
print(tabulate(res, tablefmt="github"))
